Imports VB = Microsoft.VisualBasic

Friend Class frmDataEntry
    Inherits System.Windows.Forms.Form
    Private WithEvents dgvhData As WRDB.Controls.DGVEditor

    Private WithEvents dgvhHeader As WRDB.Controls.DGVEditor

    'following contains all valid headings for columns by category as semi-colon separated lists
    '(it will be easy and fast to do string search for valid entries)

    Dim HeaderFile As String

    Private Initializing As Boolean

    Dim TreeList As String 'contains pcodes and all field names for drop-down display
    Private TreeviewForm As frmTreeView

    Private WRDBImport As clsWRDBImport
    Private LoadLastHeaderOnStartup As Boolean 'if true, will load last header in Load event

    Friend Sub New(ByRef _WRDBImport As clsWRDBImport, _LoadLastHeaderOnStartup As Boolean)
        Me.New()
        WRDBImport = _WRDBImport
        LoadLastHeaderOnStartup = _LoadLastHeaderOnStartup
        With WRDBImport
            TreeList = String.Format("Ignore;PCodes;>;{0};<;Station IDs;>;{1};<;Other Data Fields;>;Station_ID;LEW_Pct;Depth_M;CCode;SCode;LCode;QCode;Agency;<",
                                     .ValidValueList(clsWRDBImport.enumTables.tPCodeTable),
                                     .ValidValueList(clsWRDBImport.enumTables.tStationTable))
        End With
    End Sub

    Friend Property SomeAdded As Boolean = False

    ''' <summary>
    ''' Open and read test file or database table and place info into header data structure according to currently selected file format. 
    ''' </summary>
    ''' <param name="SkipPreview">True to bypass display of preview and just do import</param>
    ''' <returns></returns>
    ''' <remarks>When done, file table remains open and positioned at first line in the body.
    '''             Note: some legacy files are formatted as, say, Tabular, but don't have the
    '''             TABULAR keyword at the top. These files will not be automatically recognized.
    '''             The user will either have to add the appropriate keyword, or remove the
    '''             header entirely and respecify it.</remarks>
    Public Function ReadHeader(Optional ByRef SkipPreview As Boolean = False) As Boolean
        Dim sr As IO.StreamReader = Nothing
        Try
            With WRDBImport

                Dim IniFile As WRDB.IniFile.clsIniFile = Nothing

                If Not SkipPreview Then
                    GetHeaderFromForm()
                    If HeaderFile <> "" Then
                        IniFile = New WRDB.IniFile.clsIniFile(HeaderFile, True)
                        .UseHeadings = GetKey(IniFile, "General", "UseHeadings", CStr(True))
                        .DataFormat = GetKey(IniFile, "General", "Format", CStr(clsWRDBImport.enumFormat.Tabular))
                    End If
                End If

                Initializing = True 'don't allow changes to form to call back here

                .Increment = 1
                .IncrementType = clsWRDBImport.enumIncrement.incrRow

                .Description = ""
                .StationID = ""
                .StationGroup = ""
                .NumCols = 100
                .Increment = 1
                .IncrementType = clsWRDBImport.enumIncrement.incrRow
                .DST = False
                .PCode = ""
                .PCodeGroup = ""
                .CCode = ""
                .DataAgency = ""
                .LCode = ""
                .SCode = ""
                .QCode = ""
                .Multiplier = 1

                For c As Integer = 0 To .NumCols - 1
                    .Columns(c) = "Ignore"
                    .CCodes(c) = ""
                    .Multipliers(c) = 1
                    .ConversionGroups(c) = "(None)"
                    .Filters(c) = ""
                    .Depths(c) = Double.NaN
                Next c

                If HeaderFile <> "" Then
                    .CCode = GetKey(IniFile, "General", "CCode")
                    .Description = GetKey(IniFile, "General", "Description")
                    .DST = GetKey(IniFile, "General", "DST", CStr(False))
                    .Increment = GetKey(IniFile, "General", "Increment", CStr(1))
                    .IncrementType = GetKey(IniFile, "General", "IncrementType", CStr(clsWRDBImport.enumIncrement.incrRow))
                    .LCode = GetKey(IniFile, "General", "LCode")
                    .SCode = GetKey(IniFile, "General", "SCode")
                    .QCode = GetKey(IniFile, "General", "QCode")
                    .Multiplier = GetKey(IniFile, "General", "Multiplier", 1)
                    .NumCols = GetKey(IniFile, "General", "NumCols", CStr(0))
                    .OtherDelimiter = GetKey(IniFile, "General", "OtherDelimiter", "|")
                    .PCode = GetKey(IniFile, "General", "PCode")
                    .PCodeGroup = GetKey(IniFile, "General", "PCodeGroup")
                    .StationID = GetKey(IniFile, "General", "StationID")
                    .StationGroup = GetKey(IniFile, "General", "StationGroup")
                    .DataMonth = GetKey(IniFile, "General", "Month", "0")
                    .DataDay = GetKey(IniFile, "General", "Day", "0")
                    .DataYear = GetKey(IniFile, "General", "Year", "0")
                    .DataTime = GetKey(IniFile, "General", "Time", "")
                    .DataAgency = GetKey(IniFile, "General", "Agency", "")
                    .PCodeGroup = GetKey(IniFile, "General", "PCodeGroup", "")
                    .StationGroup = GetKey(IniFile, "General", "StationGroup", "")
                    .ValidateSupport = GetKey(IniFile, "General", "ValidateSupport", CStr(True))
                    .RCodeConvGroup = GetKey(IniFile, "General", "ConvertRCodes", CStr(False))
                    .LEW_Pct = GetKey(IniFile, "General", "LEW_Pct", "")
                    .Depth_M = GetKey(IniFile, "General", "Depth_M", "")
                    .CultureName = GetKey(IniFile, "General", "CultureName", "(Current")
                    .AutoIncrement = GetKey(IniFile, "General", "AutoIncrement", "No Auto Increment")
                    For c As Integer = 0 To .NumCols - 1
                        .CCodes(c) = GetKey(IniFile, "CCodes", CStr(c + 1))
                        .Columns(c) = GetKey(IniFile, "Columns", CStr(c + 1))
                        .Multipliers(c) = GetKey(IniFile, "Multipliers", CStr(c + 1), CStr(1))
                        .ConversionGroups(c) = GetKey(IniFile, "ConversionGroups", CStr(c + 1), "(None)")
                        .Filters(c) = GetKey(IniFile, "Filters", CStr(c + 1), "")
                        .Depths(c) = GetKey(IniFile, "Depths", CStr(c + 1), Double.NaN)
                    Next c
                    Dim sDelim As String = GetKey(IniFile, "General", "Delimiter", ",")
                    .Delimiters = sDelim.Replace("<TAB>", vbTab)
                End If

            End With

            Return True

        Catch ex As Exception
            ErrorMsg(, ex)
            Return False
        Finally
            If sr IsNot Nothing Then
                sr.Close()
                sr.Dispose()
                sr = Nothing
            End If
            Initializing = False
        End Try

    End Function

    Private Sub btnAdd_Click(ByVal eventSender As System.Object, ByVal eventArgs As System.EventArgs) Handles btnAdd.Click
        With WRDBImport
            GetHeaderFromForm()
            .WRDBDataSource.Close()
            Dim sw As New IO.StreamWriter(.ImportFilename, False)
            With dgvData
                .EndEdit()
                For r As Integer = -1 To .Rows.Count - 1
                    For c As Integer = 0 To .Columns.Count - 1
                        'If Not String.Equals(.Columns(c).HeaderText, "Ignore", StringComparison.OrdinalIgnoreCase) Then
                        If r = -1 Then
                            sw.Write(IIf(c = 0, "", vbTab) & .Columns(c).HeaderText)
                        Else
                            sw.Write(IIf(c = 0, "", vbTab) & TestNull(.Item(c, r).Value, ""))
                            SomeAdded = True
                        End If
                        'End If
                    Next
                    sw.WriteLine()
                Next
                sw.Close()
                sw.Dispose()
            End With
            .WRDBDataSource.Close()
            .WRDBDataSource = New WRDB.DataSource.clsDataText
            .WRDBDataSource.Initialize(.ImportFilename)
            .ValidateSupport = True
            SaveHeader(MyDataPath() & "\LastDataEntry.hdr")
            .Import()
        End With
        WRDBImport.WRDBDataSource.Close()
    End Sub

    Private Sub btnHelp_Click(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles btnHelp.Click
        Dim FileName As String = WRDB.Project.clsProject.HelpFilePath("WRDB.chm")
        If Not My.Computer.FileSystem.FileExists(FileName) Then
            WarningMsgFmt("Unable to find help file named '{0}'; please restore this file or reinstall application.", FileName.Replace("\", "\\"))
        Else
            Help.ShowHelp(Me, FileName, HelpNavigator.TopicId, "18")
        End If
    End Sub

    Private Sub btnLoad_Click(ByVal eventSender As System.Object, ByVal eventArgs As System.EventArgs) Handles btnLoad.Click
        Dim i As Short

        With WRDBImport

            If .ImportFilename Like "*]" Then
                HeaderFile = .ImportFilename & ".hdr"
            Else
                i = InStrRev(.ImportFilename, ".")
                HeaderFile = VB.Left(.ImportFilename, i) & "hdr"
            End If

            With New OpenFileDialog
                .Filter = "Header Files (*.hdr)|*.hdr"
                .InitialDirectory = GetSetting(RegApp, Me.Name, "HeaderDir", My.Computer.FileSystem.SpecialDirectories.MyDocuments & "\WRDB")
                .Title = "Open Header File"
                .DefaultExt = ".hdr"
                .AddExtension = True
                .FileName = IO.Path.GetFileName(HeaderFile)
                If .ShowDialog(Me) = DialogResult.Cancel Then .Dispose() : Exit Sub
                SaveSetting(RegApp, Me.Name, "HeaderDir", IO.Path.GetDirectoryName(.FileName))
                HeaderFile = .FileName
                .Dispose()
            End With
            ReadHeader()
            RefreshHeader()
            .NumCols = dgvData.ColumnCount
        End With
        SetFocusToGrid()
    End Sub

    Public Sub LoadLastHeader()
        HeaderFile = MyDataPath() & "\LastDataEntry.hdr"
        If My.Computer.FileSystem.FileExists(HeaderFile) Then
            ReadHeader()
            RefreshHeader()
            WRDBImport.NumCols = dgvData.ColumnCount
        End If
    End Sub

    Private Sub btnLoadLast_Click(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles btnLoadLast.Click
        LoadLastHeader()
        SetFocusToGrid()
    End Sub

    Private Sub btnSave_Click(ByVal eventSender As System.Object, ByVal eventArgs As System.EventArgs) Handles btnSave.Click
        Dim i As Short

        With WRDBImport

            If HeaderFile = "" Then 'let default name be same as database and table
                If .ImportFilename Like "*]" Then
                    HeaderFile = .ImportFilename & ".hdr"
                Else
                    i = InStrRev(.ImportFilename, ".")
                    HeaderFile = VB.Left(.ImportFilename, i) & "hdr"
                End If
            End If

            With New SaveFileDialog
                .Filter = "Header File (*.hdr)|*.hdr"
                .DefaultExt = ".hdr"
                .AddExtension = True
                .CheckPathExists = True
                .OverwritePrompt = True
                .SupportMultiDottedExtensions = False
                .InitialDirectory = GetSetting(RegApp, Me.Name, "HeaderDir", My.Computer.FileSystem.SpecialDirectories.MyDocuments & "\WRDB")
                .Title = "Save Header File"
                .FileName = IO.Path.GetFileName(HeaderFile)
                If .ShowDialog(Me) = Windows.Forms.DialogResult.Cancel Then .Dispose() : Exit Sub
                SaveSetting(RegApp, Me.Name, "HeaderDir", IO.Path.GetDirectoryName(.FileName))
                HeaderFile = .FileName
                .Dispose()
            End With

            SaveHeader(HeaderFile)
        End With

    End Sub

    Private Sub dgvDefaults_DataError(ByVal sender As Object, ByVal e As System.Windows.Forms.DataGridViewDataErrorEventArgs)
        Static AlreadyShown As Boolean = False
        If Not AlreadyShown Then ErrorMsg(, e.Exception)
        AlreadyShown = True
    End Sub

    Private Sub dgvData_CellEnter(ByVal sender As Object, ByVal e As System.Windows.Forms.DataGridViewCellEventArgs) Handles dgvData.CellEnter
        If e.RowIndex > 0 AndAlso (dgvData.Item(0, e.RowIndex).Value Is Nothing OrElse IsDBNull(dgvData.Item(0, e.RowIndex).Value)) AndAlso IsDate(dgvData.Item(0, e.RowIndex - 1).Value) Then
            Dim PriorDate As Date = dgvData.Item(0, e.RowIndex - 1).Value
            Dim NextDate As Date
            Select Case WRDBImport.AutoIncrement
                Case "No Auto Increment" : Exit Sub
                Case "Repeat Prior" : NextDate = PriorDate
                Case "15 Minutes" : NextDate = PriorDate.AddMinutes(15)
                Case "1 Hour" : NextDate = PriorDate.AddHours(1)
                Case "6 Hours" : NextDate = PriorDate.AddHours(6)
                Case "12 Hours" : NextDate = PriorDate.AddHours(12)
                Case "1 Day" : NextDate = PriorDate.AddDays(1)
                Case "1 Week" : NextDate = PriorDate.AddDays(7)
                Case "1 Month" : NextDate = PriorDate.AddMonths(1)
            End Select
            dgvData.Item(0, e.RowIndex).Value = NextDate
        End If
    End Sub

    Private Sub dgvData_ColumnHeaderMouseClick(ByVal sender As Object, ByVal e As System.Windows.Forms.DataGridViewCellMouseEventArgs) Handles dgvData.ColumnHeaderMouseClick
        If e.ColumnIndex = 0 Then 'is date column
            If TreeviewForm IsNot Nothing Then TreeviewForm.Dispose()
            TreeviewForm = New frmTreeView("No Auto Increment;Repeat Prior;15 Minutes;1 Hour;6 Hours;12 Hours;1 Day;1 Week;1 Month;Ignore")
        Else 'is link; show treeview
            If TreeviewForm Is Nothing Then TreeviewForm = New frmTreeView(TreeList)
        End If
        With dgvData
            Dim pt As Point = .GetCellDisplayRectangle(e.ColumnIndex, e.RowIndex, True).Location
            pt.Offset(0, .GetCellDisplayRectangle(e.ColumnIndex, e.RowIndex, True).Height)
            TreeviewForm.Location = .PointToScreen(pt)
            If TreeviewForm.ShowDialog(Me) = Windows.Forms.DialogResult.OK Then
                If e.ColumnIndex = 0 Then
                    WRDBImport.AutoIncrement = TreeviewForm.SelectedItem
                    dgvData.Columns(e.ColumnIndex).ToolTipText = WRDBImport.AutoIncrement
                    dgvData.Columns(0).ReadOnly = (WRDBImport.AutoIncrement = "Ignore")
                Else
                    dgvData.Columns(e.ColumnIndex).HeaderText = TreeviewForm.SelectedItem
                End If
            End If
            .SelectionMode = DataGridViewSelectionMode.CellSelect
            .Item(e.ColumnIndex, 0).Selected = True
        End With
        If e.ColumnIndex = 0 Then
            TreeviewForm.Dispose()
            TreeviewForm = Nothing
        End If
    End Sub

    Private Sub frmPreviewData_FormClosed(ByVal eventSender As System.Object, ByVal eventArgs As System.Windows.Forms.FormClosedEventArgs) Handles Me.FormClosed
        If TreeviewForm IsNot Nothing Then TreeviewForm.Dispose()
        SaveWindowPos(RegApp, Me)
    End Sub

    Private Sub frmPreviewData_Load(ByVal eventSender As System.Object, ByVal eventArgs As System.EventArgs) Handles MyBase.Load
        GetWindowPos(RegApp, Me)
        ReplaceTooltipAndHelpText(Me, Nothing, HelpProvider1)
        With dgvData
            .RowCount = 1000
            .ColumnHeadersVisible = True
            .ScrollBars = ScrollBars.Both
        End With
        Show()
        Initialize()
        Application.DoEvents()
        Me.BringToFront()
    End Sub

    Private Sub GetHeaderFromForm()
        With WRDBImport
            .UseHeadings = True
            .Increment = 1
            .IncrementType = clsWRDBImport.enumIncrement.incrRow
            .DST = chkDST.Checked
            .OtherDelimiter = vbTab
            .Delimiters = vbTab

            .Description = txtDescription.Text
            .StationID = WRDBProject.GetPickList(cboStationID)
            .PCode = WRDBProject.GetPickList(cboPCode)
            .CCode = WRDBProject.GetPickList(cboCCode)
            .QCode = WRDBProject.GetPickList(cboQCode)
            .DataAgency = WRDBProject.GetPickList(cboAgency)
            .LEW_Pct = txtLEW.Text
            .Depth_M = txtDepth.Text

            For i As Integer = 0 To dgvData.ColumnCount - 1
                .Columns(i) = dgvData.Columns(i).HeaderText
            Next i
        End With

    End Sub

    Public Sub Initialize()

        Dim ext As String

        With WRDBImport
            ext = IO.Path.GetExtension(.ImportFilename).ToUpper

            Initializing = True 'so changing state doesn't trigger reread

            If WRDBImport.AssumeSupport Then
                For i As Integer = 2 To tblDefaults.Controls.Count - 1
                    tblDefaults.Controls(i).Visible = False
                Next
            End If

            .ValidateSupport = GetSetting(RegApp, "General", "ValidateSupport", True)
            .RCodeConvGroup = GetSetting(RegApp, "General", "RCodeConvGrp", "(None)")
            .CultureName = GetSetting(RegApp, "General", "CultureName", "(Current)")

        End With

        For i As Integer = 1 To 5
            WRDBProject.FillPickList(Choose(i, cboStationID, cboPCode, cboCCode, cboQCode, cboAgency),
                                                "",
                                                Choose(i, "Stations", "PCodes", "CCodes", "QCodes", "Agencies"),
                                                Choose(i, "Station_ID", "PCode", "CCode", "QCode", "Agency"),
                                                Choose(i, "Station_Name", "Anal_Name", "CCode_Name", "QCode_Name", "Agency_Name"),
                                                "(Create New)",
                                                "")
        Next

        Initializing = False

        LoadForm()

    End Sub

    Private Sub LoadForm()
        If Initializing Then Exit Sub
        If Not ReadHeader() Then
            WarningMsg("The format that was detected for this file requires a specific arrangement of data, however the file header could not be properly interpreted; please check the file and compare with the requirements described in the help manual.")
            Exit Sub
        End If
        RefreshHeader()
        PreviewData()
        If LoadLastHeaderOnStartup Then LoadLastHeader()
    End Sub

    ''' <summary>
    ''' Read body of data file and place up to 50000 lines in preview grid assumed input file (or table) is already open and positioned to the record following the header for this type of import file.
    ''' </summary>
    ''' <remarks>Will close file/data reader when done</remarks>
    Private Sub PreviewData()
        Application.UseWaitCursor = True
        Application.DoEvents()

        With dgvData
            .RowCount = 1000
            .ColumnCount = 50
            .RowHeadersDefaultCellStyle.Alignment = DataGridViewContentAlignment.MiddleRight
            .RowHeadersVisible = True

            .ColumnHeadersVisible = True
            .ColumnHeadersDefaultCellStyle.Alignment = DataGridViewContentAlignment.MiddleCenter

            dgvhData = New WRDB.Controls.DGVEditor(dgvData, WRDBImport.GridFont, WRDB.Controls.DGVEditor.enumReportScaling.ScaledFonts, WRDBImport.printDoc)
            With dgvhData
                .AutoNumberRows = True
                .RenumberRows()
                .AutoReplaceDecimalSeparator = WRDB.Controls.DGVEditor.enumAutoReplaceDecimalSeparator.AllCells
            End With

            .AutoResizeRowHeadersWidth(DataGridViewRowHeadersWidthSizeMode.AutoSizeToAllHeaders)
            .AllowUserToResizeRows = False

            .EnableHeadersVisualStyles = False
            .ColumnHeadersHeightSizeMode = DataGridViewColumnHeadersHeightSizeMode.DisableResizing
            .ColumnHeadersHeight = 30

            With .ColumnHeadersDefaultCellStyle
                .Font = New Font(.Font, FontStyle.Underline)
                .ForeColor = Color.Blue
            End With

            .SelectionMode = DataGridViewSelectionMode.CellSelect

            'reset column widths
            With dgvData
                For c As Integer = 0 To .ColumnCount - 1
                    .Columns(c).AutoSizeMode = DataGridViewAutoSizeColumnMode.DisplayedCells
                Next c
            End With
        End With

        Application.UseWaitCursor = False
    End Sub

    Private Sub RefreshHeader()

        'place contents of header data structure on form; this data structure may have been filled
        'by contents of file or by loading a header file

        Initializing = True 'don't allow changes to form to call back here

        With WRDBImport

            'fill controls common to all formats (some may not be visible)

            chkDST.Checked = .DST

            txtDescription.Text = .Description
            WRDBProject.SetPickList(cboStationID, .StationID)
            WRDBProject.SetPickList(cboPCode, .PCode)
            WRDBProject.SetPickList(cboCCode, .CCode)
            WRDBProject.SetPickList(cboQCode, .QCode)
            WRDBProject.SetPickList(cboAgency, .DataAgency)
            txtLEW.Text = .LEW_Pct
            txtDepth.Text = .Depth_M

            dgvhHeader = New WRDB.Controls.DGVEditor(dgvData, WRDBImport.GridFont, WRDB.Controls.DGVEditor.enumReportScaling.ScaledFonts, WRDBImport.printDoc)

            'format for header
            With dgvData
                .ColumnCount = WRDBImport.NumCols
                .RowCount = 1000
                .RowHeadersDefaultCellStyle.Alignment = DataGridViewContentAlignment.MiddleLeft
                .ColumnHeadersDefaultCellStyle.Alignment = DataGridViewContentAlignment.MiddleCenter
                .AutoResizeRowHeadersWidth(DataGridViewRowHeadersWidthSizeMode.AutoSizeToAllHeaders)
                .CurrentCell = .Item(0, 0)
                .ScrollBars = ScrollBars.Both
                .RowHeadersVisible = True
                With .ColumnHeadersDefaultCellStyle
                    .Font = New Font(.Font, FontStyle.Underline)
                    .ForeColor = Color.Blue
                End With
                With .Columns(0)
                    .HeaderText = "Date_Time"
                    .ToolTipText = WRDBImport.AutoIncrement
                    .ValueType = GetType(Date)
                    .DefaultCellStyle.Format = MyDateTimeFormat()
                End With
                For c As Integer = 1 To .ColumnCount - 1
                    .Columns(c).HeaderText = WRDBImport.Columns(c)
                Next
            End With
        End With

        Initializing = False

    End Sub

    Private Sub SaveHeader(ByVal HeaderFile As String)
        GetHeaderFromForm()

        If My.Computer.FileSystem.FileExists(HeaderFile) Then My.Computer.FileSystem.DeleteFile(HeaderFile)

        Dim IniFile As New WRDB.IniFile.clsIniFile(HeaderFile, True)

        With WRDBImport
            IniFile.SetKeyText("General", "UseHeadings", .UseHeadings)
            IniFile.SetKeyText("General", "CCode", .CCode)
            IniFile.SetKeyText("General", "Description", .Description)
            IniFile.SetKeyText("General", "DST", .DST)
            IniFile.SetKeyText("General", "Format", .DataFormat)
            IniFile.SetKeyText("General", "Increment", .Increment)
            IniFile.SetKeyText("General", "IncrementType", .IncrementType)
            IniFile.SetKeyText("General", "Month", .DataMonth)
            IniFile.SetKeyText("General", "Multiplier", .Multiplier)
            IniFile.SetKeyText("General", "NumCols", .NumCols)
            IniFile.SetKeyText("General", "OtherDelimiter", .OtherDelimiter)
            IniFile.SetKeyText("General", "PCode", .PCode)
            IniFile.SetKeyText("General", "LCode", .LCode)
            IniFile.SetKeyText("General", "SCode", .SCode)
            IniFile.SetKeyText("General", "QCode", .QCode)
            IniFile.SetKeyText("General", "StationID", .StationID)
            IniFile.SetKeyText("General", "Time", .DataTime)
            IniFile.SetKeyText("General", "Day", .DataDay)
            IniFile.SetKeyText("General", "Year", .DataYear)
            IniFile.SetKeyText("General", "ValidateSupport", .ValidateSupport)
            IniFile.SetKeyText("General", "ConvertRCodes", .RCodeConvGroup)
            IniFile.SetKeyText("General", "CultureName", .CultureName)
            IniFile.SetKeyText("General", "Agency", .DataAgency)
            IniFile.SetKeyText("General", "PCodeGroup", .PCodeGroup)
            IniFile.SetKeyText("General", "StationGroup", .StationGroup)
            IniFile.SetKeyText("General", "LEW_Pct", .LEW_Pct)
            IniFile.SetKeyText("General", "Depth_M", .Depth_M)
            IniFile.SetKeyText("General", "AutoIncrement", .AutoIncrement)
            For i As Integer = 0 To .NumCols - 1
                IniFile.SetKeyText("CCodes", CStr(i + 1), .CCodes(i))
                IniFile.SetKeyText("Columns", CStr(i + 1), .Columns(i))
                IniFile.SetKeyText("Multipliers", CStr(i + 1), .Multipliers(i))
                IniFile.SetKeyText("ConversionGroups", CStr(i + 1), .ConversionGroups(i))
                IniFile.SetKeyText("Filters", CStr(i + 1), .Filters(i))
                IniFile.SetKeyText("Depths", CStr(i + 1), .Depths(i))
            Next i
            IniFile.SetKeyText("General", "Delimiter", .Delimiters.Replace(vbTab, "<TAB>"))

            IniFile.Save()
        End With
    End Sub

    Private Sub lnkRemoveUnused_Click(ByVal sender As Object, ByVal e As System.EventArgs) Handles lnkRemoveUnused.Click
        With dgvData
            If lnkRemoveUnused.Text.Contains("Unused") Then
                For c As Integer = .Columns.Count - 1 To 1 Step -1
                    If .Columns(c).HeaderText = "Ignore" Then .Columns.RemoveAt(c)
                Next
                lnkRemoveUnused.Text = "Add Column to Right"
            Else
                .ColumnCount += 1
                With .Columns(.ColumnCount - 1)
                    .HeaderText = "Ignore"
                    .SortMode = DataGridViewColumnSortMode.NotSortable
                    .AutoSizeMode = DataGridViewAutoSizeColumnMode.DisplayedCells
                End With
            End If
            WRDBImport.NumCols = .ColumnCount
        End With
    End Sub

    Private Sub btnClear_Click(ByVal sender As Object, ByVal e As System.EventArgs) Handles btnClear.Click
        dgvData.Rows.Clear()
        dgvData.RowCount = 1000
        dgvhData.RenumberRows()
    End Sub

    Private Sub txtMonth_Validating(sender As System.Object, e As System.ComponentModel.CancelEventArgs)
        Dim txt As TextBox = CType(sender, TextBox)
        If txt.Text.Trim <> "" AndAlso (Not IsNumeric(txt.Text) OrElse Val(txt.Text) < 1 OrElse Val(txt.Text) > 12) Then
            txt.SelectAll()
            Beep()
            e.Cancel = True
        End If
    End Sub

    Private Sub txt_KeyPress(sender As Object, e As KeyPressEventArgs) Handles txtLEW.KeyPress, txtDepth.KeyPress
        'when type decimal point, like Excel always replace with comma if that is what is dictated by culture setting
        If e.KeyChar = "." Then
            e.KeyChar = Globalization.CultureInfo.CurrentCulture.NumberFormat.NumberDecimalSeparator
        End If
    End Sub

    Private Sub txt_Validating(sender As System.Object, e As System.ComponentModel.CancelEventArgs) Handles txtLEW.Validating, txtDepth.Validating
        Dim txt As TextBox = CType(sender, TextBox)
        If txt.Text.Trim <> "" AndAlso Not IsNumeric(txt.Text) Then
            txt.SelectAll()
            Beep()
            e.Cancel = True
        End If
    End Sub

    Private Sub txtDay_Validating(sender As System.Object, e As System.ComponentModel.CancelEventArgs)
        Dim txt As TextBox = CType(sender, TextBox)
        If txt.Text.Trim <> "" AndAlso (Not IsNumeric(txt.Text) OrElse Val(txt.Text) < 1 OrElse Val(txt.Text) > 31) Then
            txt.SelectAll()
            Beep()
            e.Cancel = True
        End If
    End Sub

    Private Sub txtYear_Validating(sender As System.Object, e As System.ComponentModel.CancelEventArgs)
        Dim txt As TextBox = CType(sender, TextBox)
        If txt.Text.Trim <> "" AndAlso (Not IsNumeric(txt.Text) OrElse Val(txt.Text) < 1800 OrElse Val(txt.Text) > 2100) Then
            txt.SelectAll()
            Beep()
            e.Cancel = True
        End If
    End Sub

    Private Sub txtTime_Validating(sender As System.Object, e As System.ComponentModel.CancelEventArgs)
        Dim txt As TextBox = CType(sender, TextBox)
        If txt.Text.Trim <> "" AndAlso Not IsDate(txt.Text) Then
            txt.SelectAll()
            Beep()
            e.Cancel = True
        End If
    End Sub

    Private Sub txt_GotFocus(sender As System.Object, e As System.EventArgs) Handles txtLEW.GotFocus, txtDescription.GotFocus, txtDepth.GotFocus
        CType(sender, TextBox).SelectAll()
    End Sub

    Private Sub cbo_SelectionChangeCommitted(sender As System.Object, e As System.EventArgs) Handles cboStationID.SelectionChangeCommitted, cboQCode.SelectionChangeCommitted, cboPCode.SelectionChangeCommitted, cboCCode.SelectionChangeCommitted, cboAgency.SelectionChangeCommitted
        With CType(sender, ComboBox)
            If .Text = "(Create New)" Then
                Dim Item As String = InputBox("Enter the new item you wish to add (later you can edit the Support table to add the name/description and other fields):", "Create New Item").ToUpper
                If Item = "" Then
                    .SelectedIndex = 0
                Else
                    .Items.Add(Item)
                    .Text = Item
                End If
            End If
        End With
    End Sub

    Private Sub btnJournal_Click(sender As System.Object, e As System.EventArgs) Handles btnJournal.Click
        Dim s As String = InputBox("Enter additional information that will be included in the Journal entry for this operation:", "Journal Entry", WRDBImport.JournalDescription)
        If s <> "" Then WRDBImport.JournalDescription = s
    End Sub

    ''' <summary>
    ''' Make first character upper case
    ''' </summary>
    Private Sub txt_TextChanged(sender As System.Object, e As System.EventArgs) Handles txtDescription.TextChanged
        Dim txt As TextBox = sender
        If txt.Text.Length = 1 Then
            txt.Text = txt.Text.ToUpper
            txt.SelectionStart = 1
        End If
    End Sub

    Private Sub SetFocusToGrid()
        dgvData.Select()
        dgvData.CurrentCell = dgvData.Item(0, 1) 'do this to make it highlight cell like we want to
        dgvData.CurrentCell = dgvData.Item(0, 0)
    End Sub

    Private Sub frmDataEntry_Shown(sender As Object, e As System.EventArgs) Handles Me.Shown
        SetFocusToGrid()
    End Sub

End Class